class ProcessInstance < ActiveRecord::Base
  include RBPM::Execute

  # 开始执行
  def start
    if self.start_at.nil?
      self.update_attributes start_at: Time.now

      doc = RBPM::Parser.read(self.process_define.current_version.bpmn_file)
      # 自动执行引擎
      auto_run RBPM::Engine.start_event(doc, self).next
    else
      raise RBPM::RunTimeError.new('instance already started!')
    end
  end

  # 整个流程结束
  def finish!
    raise RBPM::RunTimeError.new('there are more than one ActiveInstance still working!') if working_active_instances.length!=0
    self.update_attributes!(end_at: Time.now, status: 0)
  end

  # 状态标题
  def status_title
    case self.status
      when 0
        '完成'
      when 1
        '启动'
      when 2
        '暂停'
      when 3
        '异常'
      else
        '未知'
    end
  end

  # 还没结束，正在运作的实例
  def working_active_instances
    self.process_active_instances.where('end_date is null')
  end
end